const db = require("../../config/db");
const md5 = require("md5");
const myRondom = "&*^^%&**##$%$";
let { HOST_URL } = require("../../config/host");
let user_avators = ["/img/1.jpg", "/img/2.jpg", "/img/3.jpg", "/img/4.jpg", "/img/5.jpg", "/img/6.jpg"];
let rd = () => {
    return Math.floor(Math.random() * user_avators.length);
};
const JwtUtil = require("../../utils/jwt");

const register = (user_acc, user_pwd, user_nick_name, create_time) => {
    return new Promise((resolve, reject) => {
        let user_check_sql = `select * from admin_user where user_acc = "${user_acc}"`;
        db.query(user_check_sql, (error, result) => {
            if (error) {
                reject({
                    code: -1,
                    msg: "查询用户异常。",
                    error,
                });
            } else {
                if (result.length == 0) {
                    let avator = HOST_URL + user_avators[rd()];
                    let user_insert_sql = `insert into admin_user(user_acc,user_pwd,user_nick_name,create_time,user_img) values("${user_acc}","${md5(
                        md5(user_pwd) + myRondom
                    )}","${user_nick_name}","${create_time}","${avator}")`;
                    db.query(user_insert_sql, (err, rows) => {
                        if (err) {
                            reject({
                                code: -1,
                                msg: "用户注册失败。",
                                err,
                            });
                        } else {
                            resolve({
                                code: 200,
                                msg: "用户注册成功。",
                                rows,
                            });
                        }
                    });
                } else {
                    resolve({
                        code: 201,
                        msg: "该账号已经存在。",
                    });
                }
            }
        });
    });
};
const login = (user_acc, user_pwd) => {
    return new Promise((resolve, reject) => {
        let user_select_sql = `select * from admin_user where user_acc = "${user_acc}"`;
        db.query(user_select_sql, (error, result) => {
            if (error) {
                reject({
                    code: -1,
                    msg: "查询用户异常。",
                    error,
                });
            } else {
                if (result.length == 0) {
                    console.log(46545, result.length);
                    reject({
                        code: 201,
                        msg: "该账号未注册。",
                    });
                } else {
                    let user_select_pwd = `select * from admin_user where user_acc = "${user_acc}"`;
                    db.query(user_select_pwd, (err, res) => {
                        if (res[0].user_pwd != md5(md5(user_pwd) + myRondom)) {
                            reject({
                                code: -1,
                                msg: "用户名或密码错误。",
                                err,
                            });
                        } else {
                            let jwt = new JwtUtil(res[0].user_id);
                            let token = jwt.generateToken();
                            console.log(555, res, 555);

                            resolve({
                                code: 200,
                                res,
                                msg: "用户登录成功。",
                                token,
                            });
                        }
                    });
                }
            }
        });
    });
};
module.exports = {
    register(user_acc, user_pwd, user_nick_name, create_time) {
        // 以后需要用到邮箱验证码
        // To do ....
        return register(user_acc, user_pwd, user_nick_name, create_time);
    },
    total() {
        return new Promise((resolve, reject) => {
            // 编写统计用户人数方法
            db.query("select count(*) as total from news_user", function (error, among) {
                if (error) {
                    reject({
                        code: -1,
                        msg: "统计用户数量失败。",
                        error,
                    });
                } else {
                    resolve({
                        code: 200,
                        msg: "获取用户总人数成功。",
                        total: among[0]["total"],
                    });
                }
            });
        });
    },
    list(page_num = 1, page_size = 5) {
        // console.log({page_num, page_size})
        return new Promise((resolve, reject) => {
            let startIndex = (page_num - 1) * page_size;
            let size = page_size;
            // console.log({startIndex, size})
            // select * from tuser limit 下标[0开始],[个数];
            // 分页数据
            let sql = "select user_id, user_acc,user_nick_name,user_img,create_time from news_user limit " + startIndex + "," + size + "";
            // let sql = 'select user_acc,user_nick_name,user_avator,user_create_time from db_user'// 查询全部
            db.query(sql, function (err, rows) {
                if (err) {
                    resolve({
                        code: -1,
                        msg: "查询用户失败。",
                        err,
                    });
                } else {
                    resolve({
                        code: 200,
                        msg: "获取分页列表成功。",
                        result: rows,
                        page: {
                            page_num: page_num,
                            page_size: page_size,
                        },
                    });
                }
            });
        });
    },
    remove(user_id, user_acc) {
        return new Promise((resolve, reject) => {
            let admin_check_sql = `select user_acc from  news_user where user_id = "${user_id}" and user_acc="${user_acc}"`;
            db.query(admin_check_sql, (error, result) => {
                if (error) {
                    reject({
                        code: -1,
                        msg: "查询用户失败0。",
                        error,
                    });
                } else {
                    console.log(result);
                    if (result.length == 1) {
                        let admin_remove_sql = `delete from  news_user where user_id = "${user_id}" and user_acc="${user_acc}"`;
                        db.query(admin_remove_sql, (err, rows) => {
                            if (err) {
                                reject({
                                    code: -1,
                                    msg: "删除用户失败1。",
                                    err,
                                });
                            } else {
                                resolve({
                                    code: 200,
                                    msg: "删除用户成功。",
                                });
                            }
                        });
                    } else {
                        reject({
                            code: -1,
                            msg: "删除用户失败2。",
                        });
                    }
                }
            });
        });
    },
    search(keyword) {
        // console.log('1.0',{keyword});
        return new Promise((resolve, reject) => {
            // 根据db_user的user_acc和user_nick_name字段进行关键字查询（模糊查询）
            let user_select_sql = "select * from news_user where user_acc LIKE CONCAT('%" + keyword + "%') or user_nick_name LIKE CONCAT('%" + keyword + "%')";
            console.log({ user_select_sql });
            db.query(user_select_sql, function (err, rows) {
                if (err) {
                    resolve({
                        code: -1,
                        msg: "搜索用户失败。",
                        err,
                    });
                } else {
                    resolve({
                        code: 200,
                        msg: "搜索用户成功。",
                        result: rows,
                    });
                }
            });
        });
    },
    login(user_acc, user_pwd) {
        // 以后需要用到邮箱验证码
        // To do ....
        return login(user_acc, user_pwd);
    },
    modify_avator(admin_id, admin_avator) {
        // console.log({admin_id, admin_avator});
        return new Promise((resolve, reject) => {
            let usr_check_sql = `select * from admin_user where user_id = "${admin_id}"`;
            console.log(usr_check_sql);
            db.query(usr_check_sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "查询用户失败",
                        err,
                    });
                } else {
                    if (rows.length == 1) {
                        let admin_modify_sql = `update admin_user set user_img= "${admin_avator}" where user_id= "${admin_id}"`;
                        db.query(admin_modify_sql, (error, result) => {
                            // console.log('9.0',{admin_id, admin_avator,error});
                            if (error) {
                                reject({
                                    code: -1,
                                    msg: "修改用户头像失败。",
                                    error,
                                });
                            } else {
                                resolve({
                                    code: 200,
                                    msg: "修改用户头像成功。",
                                    admin_avator,
                                });
                            }
                        });
                    }
                }
            });
        });
    },
    selectLoginUser(admin_acc) {
        console.log({ admin_acc });
        let sql = `select * from admin_user where user_acc = "${admin_acc}"`;
        return new Promise((resolve, reject) => {
            db.query(sql, (err, row) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "查询登录用户失败",
                        err,
                    });
                } else {
                    console.log(row);
                    resolve({
                        code: 200,
                        msg: "查询登录用户成功",
                        row,
                    });
                }
            });
        });
    },
    undateUserMsg(user_acc, user_pwd, new_pwd, new_signature) {
        let sql = `select * from admin_user where user_acc = "${user_acc}" and user_pwd = '${md5(md5(user_pwd) + myRondom)}'`;
        return new Promise((resolve, reject) => {
            db.query(sql, (err, row) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: "用户账号或密码错误",
                        err,
                    });
                } else {
                    if (row.length == 0) {
                        reject({
                            code: 201,
                            msg: "密码错误",
                        });
                    } else {
                        let updata_sql = `update admin_user set user_pwd= "${md5(md5(new_pwd) + myRondom)}",user_signature= "${new_signature}"where user_acc= "${user_acc}"`;
                        db.query(updata_sql, (err2, row2) => {
                            if (err2) {
                                reject({
                                    code: -1,
                                    err2,
                                    msg: "修改失败",
                                });
                            } else {
                                resolve({
                                    code: 200,
                                    msg: "修改用户信息成功",
                                    row2,
                                });
                            }
                        });
                    }
                }
            });
        });
    },
};
